package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TSoftMapper;
import com.bwie.mapper.TTypeMapper;
import com.bwie.pojo.TSoft;
import com.bwie.pojo.TType;
import com.bwie.pojo.TUser;
import com.bwie.service.TUserService;
import com.bwie.mapper.TUserMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-06-26 09:56:41
*/
@Service
@Transactional
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TSoftMapper tSoftMapper;

    @Autowired
    private TTypeMapper tTypeMapper;

    @Override
    public R login(TUser tUser) {
        //使用JWT实现单点登录功能，登录的操作在AUTH服务进行（5分）
        //未登录的用户无法访问当前系统，使用请求头进行拦截操作（5分）
        TUser user = tUserMapper.selectOne(new QueryWrapper<TUser>().lambda().eq(TUser::getUserName, tUser.getUserName()));
        if(user==null){
            return R.ERROR(500,"用户名不存在");
        }
        if(!tUser.getUserPass().equals(user.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", user.getUserId()).compact();
        user.setToken(token);
        redisTemplate.opsForValue().set("token-"+user.getUserId(),token,60, TimeUnit.MINUTES);
        return R.OK(user);
    }

    @Override
    public R getSoftList(PageInfoVo pageInfoVo) {
        //软件商城的软件展示无问题。在软件列表上展示当前用户的用户余额（5分）
        //软件名称模糊查询，软件分类精确查询。列表分页操作无问题（5分）
        Page<TSoft> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TSoft> softList = tSoftMapper.getSoftList(page, pageInfoVo);
        return R.OK(softList);
    }

    @Override
    public R getType() {
        ////项目启动的时候需要把软件分类初始化到缓存当中。（5分）
        List<TType> tTypes=null;
        String types = redisTemplate.opsForValue().get("tTypes");
        if(types==null){
            tTypes = tTypeMapper.selectList(null);
            redisTemplate.opsForValue().set("tTypes", JSON.toJSONString(tTypes),30,TimeUnit.MINUTES);
        }else{
            tTypes=JSON.parseArray(types, TType.class);
        }
        return R.OK(tTypes);
    }
}




